import React, { useState, useRef } from 'react';
import { processJsonFile, downloadExampleJson } from '../../utils/fileUploader.js';
import ErrorModal from '../ErrorModal/index.jsx';
import './style.css';

const FileUploader = ({ onDataLoaded, onError }) => {
  const [dragActive, setDragActive] = useState(false);
  const [processing, setProcessing] = useState(false);
  const [processingStatus, setProcessingStatus] = useState('');
  const [uploadResult, setUploadResult] = useState(null);
  const [errorModalVisible, setErrorModalVisible] = useState(false);
  const [errorModalData, setErrorModalData] = useState(null);
  const fileInputRef = useRef(null);

  // 处理文件
  const handleFile = async (file) => {
    if (!file) return;

    setProcessing(true);
    setUploadResult(null);
    setProcessingStatus('正在读取文件...');

    try {
      const result = await processJsonFile(file);
      
      setUploadResult(result);
      
      if (result.success) {
        setProcessingStatus('文件处理成功');
        if (onDataLoaded) {
          onDataLoaded(result.data, result.originalData);
        }
      } else {
        setProcessingStatus('处理失败');
        // 显示错误弹窗
        setErrorModalData({
          error: result.error,
          validationResult: result.validationResult
        });
        setErrorModalVisible(true);
        
        if (onError) {
          onError(result.error, result.validationResult);
        }
      }
    } catch (error) {
      const errorMsg = `处理失败: ${error.message}`;
      setProcessingStatus('处理失败');
      
      // 显示错误弹窗
      setErrorModalData({
        error: errorMsg,
        validationResult: null
      });
      setErrorModalVisible(true);
      
      setUploadResult({
        success: false,
        error: errorMsg
      });
      if (onError) {
        onError(errorMsg);
      }
    } finally {
      setProcessing(false);
    }
  };

  // 拖拽事件处理
  const handleDrag = (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true);
    } else if (e.type === 'dragleave') {
      setDragActive(false);
    }
  };

  const handleDrop = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
    
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFile(e.dataTransfer.files[0]);
    }
  };

  // 点击上传
  const handleClick = () => {
    if (fileInputRef.current) {
      fileInputRef.current.click();
    }
  };

  const handleFileChange = (e) => {
    if (e.target.files && e.target.files[0]) {
      handleFile(e.target.files[0]);
    }
  };

  // 清除结果
  const clearResult = () => {
    setUploadResult(null);
    setProcessingStatus('');
    setErrorModalVisible(false);
    setErrorModalData(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  // 关闭错误弹窗并清除结果
  const closeErrorModal = () => {
    setErrorModalVisible(false);
    setErrorModalData(null);
    // 自动执行清除结果功能，方便用户重新上传
    setUploadResult(null);
    setProcessingStatus('');
    // 清除文件输入的值，允许选择相同文件
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  return (
    <div className="file-uploader">
      <div className="upload-area">
        <div
          className={`upload-zone ${dragActive ? 'drag-active' : ''} ${processing ? 'processing' : ''}`}
          onDragEnter={handleDrag}
          onDragLeave={handleDrag}
          onDragOver={handleDrag}
          onDrop={handleDrop}
          onClick={handleClick}
        >
          <input
            ref={fileInputRef}
            type="file"
            accept=".json"
            onChange={handleFileChange}
            style={{ display: 'none' }}
          />
          
          {processing ? (
            <div className="processing-indicator">
              <div className="spinner"></div>
              <p>{processingStatus}</p>
            </div>
          ) : (
            <div className="upload-content">
              <div className="upload-icon">📁</div>
              <p className="upload-text">
                点击或拖拽JSON文件到此处上传
              </p>
              <p className="upload-hint">
                仅支持.json格式文件，最大5MB
              </p>
            </div>
          )}
        </div>

        <div className="upload-actions">
          <button
            type="button"
            onClick={downloadExampleJson}
            className="btn btn-outline"
            disabled={processing}
          >
            下载示例文件
          </button>
          {uploadResult && (
            <button
              type="button"
              onClick={clearResult}
              className="btn btn-outline"
              disabled={processing}
            >
              清除结果
            </button>
          )}
        </div>
      </div>

      {uploadResult && uploadResult.success && (
        <div className="upload-result">
          <div className="result-header success">
            <span className="result-icon">✅</span>
            <span className="result-title">上传成功</span>
          </div>

          <div className="result-content">
            <div className="success-info">
              <p>✅ 文件解析成功</p>
              <p>✅ 数据格式验证通过</p>
              <p>✅ 数据转换完成</p>
              {uploadResult.validationResult?.warnings?.length > 0 && (
                <div className="warnings">
                  <p className="warning-title">⚠️ 警告信息:</p>
                  <ul>
                    {uploadResult.validationResult.warnings.map((warning, index) => (
                      <li key={index}>{warning}</li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      <ErrorModal
        visible={errorModalVisible}
        onClose={closeErrorModal}
        title="文件校验失败"
        error={errorModalData?.error}
        validationResult={errorModalData?.validationResult}
      />
    </div>
  );
};

export default FileUploader; 